package com.guozcc.bootweb.platform.websocket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created with IntelliJ IDEA.
 * @ Auther: guozcc
 * @ Date: 2024/03/01/14:35
 * @ Description:
 * @ ServerEndpoint 注解是一个类层次的注解，它的功能主要是将目前的类定义成一个websocket服务器端,
 * 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
 *
 * ws://127.0.0.1:8081/websocket/{sid}
 */
@Component
@Service
@ServerEndpoint("/websocket/{sid}")
public class WebSocketServer {
    private final static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    //静态变量，用来维护长连接
    private static ConcurrentHashMap<String,Session> webSocketMap = new ConcurrentHashMap<String,Session>();
    //当前对象的sid
    private String sid = null;
    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid){
        try {
            this.sid = sid;
            //查看当前sid是否存在长连接，若存在，先关闭
            Session exit = webSocketMap.get(sid);
            if(exit!=null){
                log.info("关闭当前连接，sid=" + sid);
                exit.close();
            }
            webSocketMap.put(sid,session);
            addOnlineCount();//在线数加1
            log.info("长连接创建成功，sid=" + sid + ",当前在线人数为:" + getOnlineCount());
        } catch (IOException e) {
            log.error("websocket IO Exception");
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        log.info("关闭连接，sid = " + sid);
        try {
            webSocketMap.remove(sid);
            subOnlineCount();//在线数减1
        } catch (Exception e){
            log.error("",e);
        }
        log.info("当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     * @ Param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("收到来自窗口" + sid + "的信息:" + message);
    }

    /**
     * @ Param session
     * @ Param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        log.error("",error);
        webSocketMap.remove(sid);
        try {
            session.close();
        } catch (Exception e){
            subOnlineCount();//在线数减1
            log.error("",e);
        }
    }



    /**
     * 群发自定义消息
     */
    public static void pushMsg(String message) throws IOException {
        for (String sid : webSocketMap.keySet()){
            Session session = webSocketMap.get(sid);
            session.getBasicRemote().sendText(message);
        }
    }
    /**
     * 向指定sid发送自定义消息
     */
    public static void pushMsg2Sid(String message,String sid) throws IOException {
        Session session = webSocketMap.get(sid);
        if(session==null){
            log.error("不存在长连接，sid=" + sid);
        }else {
            log.info("推送消息，sid="+sid+"，推送内容："+message);
            session.getBasicRemote().sendText(message);
        }
    }
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
    public static synchronized void addOnlineCount() {
        WebSocketServer.onlineCount++;
    }
    public static synchronized void subOnlineCount() {
        WebSocketServer.onlineCount--;
    }

}
